package com.zxy.ziems.server.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.btp.common.exception.ConditionException;
import com.zxy.btp.common.response.PageResult;
import com.zxy.ziems.server.convert.AgreementConvert;
import com.zxy.ziems.server.convert.OrgConvert;
import com.zxy.ziems.server.domain.Agreement;
import com.zxy.ziems.server.domain.AgreementChannel;
import com.zxy.ziems.server.domain.Org;
import com.zxy.ziems.server.domain.User;
import com.zxy.ziems.server.dto.AgreementDto;
import com.zxy.ziems.server.dto.AgreementQueryDto;
import com.zxy.ziems.server.mapper.AgreementMapper;
import com.zxy.ziems.server.service.AgreementChannelService;
import com.zxy.ziems.server.service.AgreementService;
import com.zxy.ziems.server.service.UserService;
import com.zxy.ziems.server.vo.AgreementVo;
import com.zxy.ziems.server.vo.OrgVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName AgreementServiceImpl
 * @Description
 * @Author 邓伟
 * @Date 2023/11/29 10:53
 * @Version 1.0
 */
@Service
public class AgreementServiceImpl extends ServiceImpl<AgreementMapper, Agreement> implements AgreementService {

    @Autowired
    private AgreementMapper agreementMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private AgreementChannelService agreementChannelService;

    @Override
    public void addOrUpdate(AgreementDto agreementDto) {
        checkName(agreementDto);
        String agreementId = agreementDto.getAgreementId();
        Agreement agreement = AgreementConvert.INSTANCE.agreementDtoToAgreement(agreementDto);
        if (StrUtil.isEmpty(agreementId)) {
            agreementMapper.insert(agreement);
        }else {
            agreementMapper.updateById(agreement);
        }
    }

    @Override
    public void delete(String agreementId) {
        //判断是否有下级通道
        QueryWrapper<AgreementChannel> query = new QueryWrapper<>();
        query.lambda().eq(AgreementChannel::getAgreementId,agreementId);
        long count = agreementChannelService.count(query);
        if (count > 0 ) {
            throw new ConditionException("协议下有配置的通道，不允许删除协议");
        }
        removeById(agreementId);
    }

    @Override
    public PageResult<AgreementVo> pageList(AgreementQueryDto agreementQueryDto) {
        //组装wrapper
        QueryWrapper<Agreement> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(ObjectUtil.isNotEmpty(agreementQueryDto.getAgreementName()),Agreement::getAgreementName,agreementQueryDto.getAgreementName());
        queryWrapper.lambda().orderByDesc(Agreement::getUpdateTime);
        Page<Agreement> page = agreementMapper.selectPage(new Page<>(agreementQueryDto.getPageNo(), agreementQueryDto.getPageSize()), queryWrapper);
        List<Agreement> records = page.getRecords();
        //空值
        if (ObjectUtil.isEmpty(records)){
            return new PageResult<>(page.getTotal(), Collections.emptyList());
        }
        List<AgreementVo> agreementVoList = AgreementConvert.INSTANCE.agreementListToAgreementVoList(records);
        List<String> userIdList = agreementVoList.stream().map(AgreementVo::getUpdateUserId).toList();
        //负责人
        Map<String,String> userMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(userIdList)){
            List<User> userList = userService.listByIds(userIdList);
            userMap = userList.stream().collect(Collectors.toMap(User::getUserId,User::getUserName));
        }
        for (AgreementVo agreementVo : agreementVoList) {
            agreementVo.setUpdateUserName(userMap.get(agreementVo.getUpdateUserId()));
        }
        return new PageResult<>(page.getTotal(),agreementVoList);
    }

    private void checkName(AgreementDto agreementDto) {
        String agreementName = agreementDto.getAgreementName();
        String agreementId = agreementDto.getAgreementId();
        QueryWrapper<Agreement> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Agreement::getAgreementName,agreementName);
        if (StrUtil.isNotEmpty(agreementId)) {
            queryWrapper.lambda().ne(Agreement::getAgreementId,agreementId);
        }
        Long count = agreementMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new ConditionException("协议名称不能重复，请修改后再保存");
        }
    }
}
